package Thread.PC;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author VX5
 * @Title: MJC
 * @ProjectName DataStructure
 * @Description: TODO
 * @date ${DAT}9:24
 *
 * 一个初始值为0的变量，两个线程对其交替操作，一个加1一个减1，进行五轮
 * 线程 操作 资源类
 * 判断 干活 通知
 * 防止虚假判断
 */

class ShareData{
    private int number = 0;
    private Lock lock = new ReentrantLock();
    private Condition condition = lock.newCondition();


    //生产者添加
    public void increment()throws Exception {
        lock.lock();
        try {
            //1 判断
            while (number != 0) {
                //等待不能生产
                condition.await();
            }
            //干活
            number++;
            System.out.println(Thread.currentThread().getName() + "\t" + number);
            //通知唤醒
            condition.signalAll();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

        public void decrement(){
            lock.lock();
            try {
                //1 判断
                while (number == 0){
                    //等待不能生产
                    condition.await();
                }
                //干活
                number--;
                System.out.println(Thread.currentThread().getName()+"\t"+number);
                //通知唤醒
                condition.signalAll();
            } catch (Exception e) {
                e.printStackTrace();
            }finally {
                lock.unlock();
            }
        }
}
public class ProdConsumer {



    public static void main(String[] args) {
        ShareData shareData = new ShareData();

        new Thread(() -> {
            for (int i = 0; i < 5; i++){
                try {
                    shareData.increment();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        },"AA").start();

        new Thread(() -> {
            for (int i = 0; i < 5; i++){
                try {
                    shareData.decrement();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        },"BB").start();
    }
}
